//
//  HomePageViewController.m
//  DaDaBao
//
//  Created by User on 15/8/12.
//  Copyright (c) 2015年 User. All rights reserved.
//
#import "JCTopic.h"
#import "RoundProgress.h"
#import "HomePageViewController.h"
#import "RecommendModel.h"
#import "DetailViewController.h"
#import "BannerModel.h"

@interface HomePageViewController ()<JCTopicDelegate>
@property (nonatomic,strong)   UIView         * backView;

@property (nonatomic,strong)   NSTimer        * timer;//动态画圈定时器

@property (nonatomic,strong)   RoundProgress  * progressView;//进度条

@property (nonatomic,strong)   UIScrollView   * mainScrollView;//大背景滑动视图

@property (nonatomic,strong)   JCTopic        * titleScrollView;

@property (nonatomic,strong)   UIPageControl  * pageControl;

@property (nonatomic,strong)  NSDictionary    *recommendDict;

@property (nonatomic,strong)  UILabel         *tipLabel;//年收益率标题

@property (nonatomic,strong)  UILabel         *rateLabel;//年收益率

@property (nonatomic,strong)  UILabel         *dateLabel;//项目时间

@property (nonatomic,strong)  UILabel         *itemLabel;//项目规模

@property (nonatomic,strong) RecommendModel   *recommendModel;

@property (nonatomic,strong)  UIButton        *tipBt;

@property (nonatomic,strong)  UILabel         *investTitleLabel;

@property (nonatomic,strong)  UIButton        *investBtn;

@property (nonatomic, strong) NSMutableArray   *imageArr;

@property (nonatomic, strong) UIImageView      *defaultImageView;

@property (nonatomic, strong) UIButton          *noneDataBt;
@property (nonatomic,strong)   UIView          * headerView;


@end

@implementation HomePageViewController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];;

    [self createTheTopicScrollView];//轮播图
}
-(void)requestData
{
    [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];
    _noneDataBt.hidden = TRUE;
    _tipBt.hidden = TRUE;
    
    //移除视图
    [_investTitleLabel removeFromSuperview];
    _investTitleLabel = nil;
    
    [_progressView removeFromSuperview];
    _progressView = nil;
    
    [_tipLabel removeFromSuperview];
    _tipLabel = nil;
    
    [_rateLabel removeFromSuperview];
    _rateLabel = nil;
    
    [_dateLabel removeFromSuperview];
    _dateLabel = nil;
    
    [_investBtn removeFromSuperview];
    _investBtn = nil;
    
    [_itemLabel removeFromSuperview];
    _itemLabel = nil;
    
    [AppGlobalClass PostDataWithNSstring:RECOMMEND_PROJECT_URL withDictionary:nil success:^(NSDictionary *dictionary){
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            NSArray *dataArray = [[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"];
            
            if(dataArray.count > 0)
            {
                _recommendModel = [[RecommendModel alloc]initWithDictionary:[dataArray firstObject]];
                [self createTheInvestView];//创建推荐项目相关控件
                
                [self performSelectorInBackground:@selector(createTimer) withObject:@"隐式创建"];//    开启分线程
                
                [self createTheInvestBtn];//投资按钮
                
                self.mainScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, _backView.frame.size.height + 64 +50);
            }
            else
            {
                _noneDataBt.hidden = FALSE;
            }
        }
        else
        {
            ALERT_VIEW([dictionary objectForKey:@"message"]);
        }
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
    } failure:^(NSError *error){
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
       _noneDataBt.hidden = FALSE;
    } networkerror:^(NSString *networkerror){
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
        _tipBt.hidden = FALSE;
    }];
}


- (void)requestBannerData
{
    _defaultImageView.hidden = TRUE;
    [AppGlobalClass PostDataWithNSstring:BANNER_URL withDictionary:nil success:^(NSDictionary *dictionary){
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            [_imageArr removeAllObjects];
            NSMutableArray *listArray = [[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"];
            
            for( int i = 0; i < listArray.count; i++ )
            {
                BannerModel *bannerModel = [[BannerModel alloc]initWithDictionary:[listArray objectAtIndex:i]];
                [_imageArr addObject:bannerModel];
            }
            
          
            
            if(_imageArr.count > 0)
            {
                [self createTimer];
                _defaultImageView.hidden = TRUE;
                _pageControl.numberOfPages = _imageArr.count;
                _titleScrollView.pics = _imageArr;
                [_titleScrollView upDate];
                
            }
            else
            {
                _defaultImageView.hidden = FALSE;
            }
        }
    } failure:^(NSError *error){ _defaultImageView.hidden = FALSE; } networkerror:^(NSString *networkerror){ _defaultImageView.hidden = FALSE;}];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _imageArr = [[NSMutableArray alloc]init];
    
    [[UIApplication sharedApplication]setStatusBarHidden:FALSE];
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
    
    TopView *topView = [[TopView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"大大宝"];
    [self.view addSubview:topView];
    
    //添加大背景scrollView
    _mainScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    _mainScrollView.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
    [self.view addSubview:_mainScrollView];
    
    //投资项目相关控件的背景图
    [_mainScrollView addSubview:self.backView];
    
    [_backView addSubview:self.tipBt];
    [_backView addSubview:self.noneDataBt];
    [_mainScrollView addSubview:self.headerView];
    
    //添加默认图片
    _defaultImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 123.0f * HSCALE)];
    _defaultImageView.image = [UIImage imageNamed:@"default"];
    _defaultImageView.hidden = TRUE;
    [_mainScrollView addSubview:_defaultImageView];
    
    [self requestData];
    [self requestBannerData];

}
-(UIView *)headerView
{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 123.0f)];
        
        _titleScrollView = [[JCTopic alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 123.0f*HSCALE)];
        _titleScrollView.JCdelegate = self;
        _pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20.0f)];
        _pageControl.center = CGPointMake(self.view.center.x, 110.0f*HSCALE);
        _pageControl.enabled = FALSE;
        [_headerView addSubview:_titleScrollView];
        [_headerView addSubview:_pageControl];

    }
    return _headerView;
}
-(UIView *)backView
{
    if (!_backView) {
        _backView = [[UIView alloc]initWithFrame:CGRectMake(5.0f, 130.0f * HSCALE, SCREEN_WIDTH - 10.0f, SCREEN_HEIGHT - 64.0f - 130.0f * HSCALE)];
        _backView.backgroundColor = [UIColor whiteColor];
    }
    return _backView;
}

- (UIButton *)noneDataBt
{
    if(!_noneDataBt)
    {
        _noneDataBt = [[UIButton alloc]initWithFrame:CGRectMake((_backView.frame.size.width  - 116.0f) / 2.0f, (_backView.frame.size.height - 130.0f) / 2.0f, 116.0f, 130.0f)];
        [_noneDataBt setImage:[UIImage imageNamed:@"img_nodata"] forState:UIControlStateNormal];
        [_noneDataBt addTarget:self action:@selector(buttonAgainTapped:) forControlEvents:UIControlEventTouchUpInside];
        _noneDataBt.hidden = TRUE;
    }
    return _noneDataBt;
}

//没网提示
-(UIButton *)tipBt
{
    if (!_tipBt) {
        _tipBt = [[UIButton alloc]initWithFrame:CGRectMake((_backView.frame.size.width  - 116.0f) / 2.0f, (_backView.frame.size.height - 130.0f) / 2.0f, 116.0f, 130.0f)];
        [_tipBt addTarget:self action:@selector(buttonAgainTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_tipBt setImage:[UIImage imageNamed:@"network_error"] forState:UIControlStateNormal];
        _tipBt.hidden = TRUE;
    }
    return _tipBt;
}

//重新请求数据
- (void)buttonAgainTapped:(id)sender
{
    [self requestData];
}

#pragma mark-----------创建轮播图
-(void)createTheTopicScrollView
{
    }
#pragma mark------------创建投资项目相关控件
-(void)createTheInvestView
{
    if (!_tipLabel) //不让重复创建
    {
        _investTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, 40*HSCALE)];
        _investTitleLabel.textAlignment = NSTextAlignmentCenter;
        _investTitleLabel.font = [UIFont systemFontOfSize:18.0f*WSCALE];
        [_backView addSubview:_investTitleLabel];
        //画圈
        _progressView = [[RoundProgress alloc]initCreateTheCircleWithFrame:CGRectMake(0, 0, 240*WSCALE, 240*WSCALE) withStartAngle:M_PI/2.0 + M_PI/3.0-M_PI/10.0 andEndAngle:M_PI/2.0 + M_PI/3.0-M_PI/10.0 andTheGrayCicleEndAngle:3*M_PI - (M_PI/2.0 + M_PI/3.0-M_PI/10.0)];
        _progressView.center = CGPointMake(self.view.center.x-5*WSCALE, 240*WSCALE/2+40*WSCALE);
        _progressView.progressWidth = 5.0f*WSCALE;
        [_backView addSubview:_progressView];
        
        //创建四个label
        _tipLabel = [[UILabel alloc]initWithFrame:CGRectMake(40*WSCALE, 30*HSCALE, 240*WSCALE - 80*WSCALE, 40*HSCALE)];
        _tipLabel.text = @"预期年化收益率";
        _tipLabel.font = [UIFont systemFontOfSize:14.0f*WSCALE];
        _tipLabel.textAlignment = NSTextAlignmentCenter;
        _tipLabel.textColor = [UIColor lightGrayColor];
        [_progressView addSubview:_tipLabel];
        
        _rateLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 55*HSCALE, 240*WSCALE, 90*HSCALE)];
        _rateLabel.font = [UIFont boldSystemFontOfSize:42.0f*WSCALE];
        _rateLabel.textAlignment = NSTextAlignmentCenter;
        _rateLabel.textColor = [UIColor hexStringToColor:RED_COLOR_VALUE];
        [_progressView addSubview:_rateLabel];
        
        _dateLabel = [[UILabel alloc]initWithFrame:CGRectMake(48*WSCALE,135*HSCALE, (240 - 96)*WSCALE, 40*HSCALE)];
        _dateLabel.font = [UIFont systemFontOfSize:14.0f*WSCALE];
        _dateLabel.textAlignment = NSTextAlignmentCenter;
        _dateLabel.textColor = [UIColor hexStringToColor:RED_COLOR_VALUE];
        [_progressView addSubview:_dateLabel];
        
        self.itemLabel = [[UILabel alloc]initWithFrame:CGRectMake(50*WSCALE,190*HSCALE, (240 - 100)*WSCALE, 25*HSCALE)];
        self.itemLabel.layer.cornerRadius = 12*WSCALE;
        self.itemLabel.layer.borderWidth = 2;
        self.itemLabel.layer.borderColor = [[UIColor colorWithRed:229.0f / 255.0f green:229.0f / 255.0f blue:229.0f / 255.0f alpha:1.0f] CGColor];
        self.itemLabel.font = [UIFont systemFontOfSize:14.0f*WSCALE];
        self.itemLabel.textAlignment = NSTextAlignmentCenter;
        self.itemLabel.textColor = [UIColor grayColor];
        [_progressView addSubview:self.itemLabel];
    }
    _investTitleLabel.text = _recommendModel.productName;
    _rateLabel.text = [NSString stringWithFormat:@"%.2f%@",[_recommendModel.expectedReturnRatio floatValue], @"%"];
    _dateLabel.text = [NSString stringWithFormat:@"项目期限%@天",_recommendModel.timeLimit];
    self.itemLabel.text = [NSString stringWithFormat:@"项目规模%.0lf万元",[_recommendModel.totalCredit doubleValue] /10000.0f];
    _progressView.endAngle = M_PI/2.0 + M_PI/3.0-M_PI/10.0;
}
#pragma mark --------创建投资按钮
-(void)createTheInvestBtn
{
    if (!_investBtn)
    {
        _investBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 200*WSCALE, 30.0f*HSCALE)];
        _investBtn.center = CGPointMake(self.view.center.x-5*WSCALE, 300*HSCALE);
        _investBtn.backgroundColor = [UIColor hexStringToColor:RED_COLOR_VALUE];
        [_investBtn setTitle:@"立即投资" forState:UIControlStateNormal];
        _investBtn.titleLabel.font = [UIFont boldSystemFontOfSize:19.0f];
        _investBtn.layer.cornerRadius = 5;
        _investBtn.layer.masksToBounds = TRUE;
        [_investBtn addTarget:self action:@selector(buttonInvestTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_investBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_backView addSubview:_investBtn];
        if ((_investBtn.frame.size.height + _investBtn.frame.origin.y)>SCREEN_HEIGHT)
        {
            _backView.frame = CGRectMake(5, 130*HSCALE, SCREEN_WIDTH-10, _investBtn.frame.size.height + _investBtn.frame.origin.y);
        }else
        {
            _backView.frame = CGRectMake(5, 130*HSCALE, SCREEN_WIDTH-10, SCREEN_HEIGHT-125);
        }

    }
}
#pragma mark-----------定时器及绑定方法
//分线程方法，开定时器
-(void)createTimer
{
    if (![NSThread isMainThread]) {
        
        if (_timer)
        {
            [_timer invalidate];
            _timer = nil;
        }
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(startLoop) userInfo:nil repeats:TRUE];
        
        //将定时器添加到runloop中
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] run];
    }
}
//timer方法画圆
-(void)startLoop
{
    if (_progressView.endAngle< M_PI/2.0 + M_PI/3.0-M_PI/10.0 + ([_recommendModel.progress floatValue] / [_recommendModel.totalCredit floatValue]) * (3*M_PI - (22*M_PI)/15.0f))//在这里更改圈的红色长度
    {
        _progressView.endAngle += 0.02;
        [_progressView setNeedsDisplay];
    }
    else
    {
        [_timer invalidate];
        _timer = nil;
    }
}
-(void)buttonInvestTapped:(id)sender
{
    if(_recommendModel.productId  == nil)
    {
        ALERT_VIEW(@"服务器异常");
    }
    else
    {
        DetailViewController *vc = [[DetailViewController alloc] initWithProjectID:_recommendModel.productId];
        [self.navigationController pushViewController:vc animated:TRUE];
    }
}
#pragma mark--------jcDelegate
- (void)didClick:(BannerModel *)bannerModel
{
    if([bannerModel.bType intValue] == 0)
    {
        self.tabBarController.selectedIndex = 1;
    }
    else
    {
        DetailViewController *detailViewCon = [[DetailViewController alloc]initWithProjectID:bannerModel.recordId];
        [self.navigationController pushViewController:detailViewCon animated:TRUE];
    }
}
-(void)currentPage:(int)page total:(NSUInteger)total
{
    _pageControl.currentPage = page;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_timer invalidate];
    self.timer = nil;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
